package com.cloud.sso.oauth.handler;

import com.alibaba.fastjson.JSON;
import com.cloud.sso.common.util.JsonContent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

@Component
public class AppLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Value("${sso.defaultRedirectUrl}")
    private String defaultRedirectUrl;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        String targetUrl;
        if (savedRequest != null) {

            targetUrl = savedRequest.getRedirectUrl();
            System.out.println("重定向地址：" + savedRequest.getRedirectUrl());
            //super.onAuthenticationSuccess(request, response, authentication);
        } else {
            // response.sendRedirect(defaultRedirectUrl);
            targetUrl = defaultRedirectUrl;
        }

        JsonContent data = JsonContent.success().setData(targetUrl);


        String jsonData = new String(JSON.toJSONString(data).getBytes(), "UTF-8");

        Writer writer = response.getWriter();

        writer.write(jsonData);
        writer.flush();
        writer.close();

    }
}
